<template>
  <view
    style="
      background-color: rgba(241, 241, 241, 1);
      padding: 30rpx;
      box-sizing: border-box;
      padding-bottom: 200rpx;
    "
  >
    <tips :message="'音乐'" :content="content"></tips>
    <view class="kong" v-if="music.length == 0">
      <image
        class="img"
        src="https://www.diandianyouke.site:801/fileDataBase/static/stag/static/img/state_empty.png"
      />
    </view>
    <view v-else class="betitle">
      <view
        class="gurudin-audio"
        :class="theme"
        v-for="(item, index) in music"
        :key="index"
        style="
          background-color: #fff;
          border-radius: 16rpx;
          margin-bottom: 24rpx;
          height: 158rpx;
          align-items: center;
          padding: 0 30rpx;
          box-sizing: border-box;
        "
      >
        <view class="gurudin-poster">
          <image
            :src="item.musicImg"
            v-if="item.musicImg != ''"
            class="musicRotate"
            :class="{ musicPaused: !audio[index].isPlay }"
          ></image>
          <view class="tools" @click="play(index)">
            <image :src="audio[index].isPlay ? icon.pause : icon.play"></image>
          </view>
        </view>
        <view class="gurudin-content">
          <view class="title">
            {{ item.musicName }}
            <view class="time"></view>
          </view>
          <view class="author">{{ item.musicAuthor }}</view>
        </view>
        <image
          @click="delMusic(index)"
          class="del"
          src="https://www.diandianyouke.site:801/fileDataBase/static/stag/static/img/button_shanchu.png"
          mode=""
        />
      </view>
    </view>
    <btn-module :message="'添加音乐'" @customClick="addMusic"></btn-module>
  </view>
  <uni-popup ref="add" @change="switchMusic">
    <view class="popup">
      <view style="display: flex; justify-content: space-evenly">
        <text class="recom" :class="isShow == 0 ? 'active' : ''" @click="choose(0)"
          >推荐</text
        >
        <text class="recom" :class="isShow == 1 ? 'active' : ''" @click="choose(1)"
          >收藏</text
        >
        <image
          @click="close"
          class="close-btn"
          src="https://www.diandianyouke.site:801/fileDataBase/static/stag/static/img/list_button_Close.png"
          mode=""
        />
      </view>
      <view style="padding: 0rpx 18rpx; height: 905rpx; overflow-y: scroll">
        <radio-group v-if="isShow == 0">
          <label
            @click="check(item, index)"
            class="label"
            v-for="(item, index) in musicArr"
            :key="index"
          >
            <view style="margin-left: 20rpx">
              <aip-checkbox :key="keys" :check="item.checked"></aip-checkbox>
            </view>
            <view class="gurudin-audio" :class="theme">
              <view class="gurudin-poster">
                <image
                  :src="item.musicImg"
                  v-if="item.musicImg != ''"
                  class="musicRotate"
                  :class="{ musicPaused: !audio[index].isPlay }"
                ></image>
                <view class="tools" @click="play(index)">
                  <image :src="audio[index].isPlay ? icon.pause : icon.play"></image>
                </view>
              </view>
              <view class="gurudin-content">
                <view class="title">
                  {{ item.musicName }}
                  <view class="time"></view>
                </view>
                <view class="author">{{ item.musicAuthor }}</view>
              </view>
              <image
                @click="getCollect(item, index)"
                class="del"
                :src="
                  !item.isCollect
                    ? 'https://www.diandianyouke.site:801/fileDataBase/static/stag/static/img/icon_scangw.png'
                    : 'https://www.diandianyouke.site:801/fileDataBase/static/stag/static/img/icon_scangy.png'
                "
                mode=""
              />
            </view>
          </label>
        </radio-group>
        <radio-group @change="radioChange" v-if="isShow == 1">
          <label
            @click="check(item, index)"
            class="label"
            v-for="(item, index) in individuality"
            :key="index"
          >
            <view style="margin-left: 20rpx">
              <aip-checkbox :key="keys" :check="item.checked"></aip-checkbox>
            </view>
            <view class="gurudin-audio" :class="theme">
              <view class="gurudin-poster">
                <image
                  :src="item.musicImg"
                  v-if="item.musicImg != ''"
                  class="musicRotate"
                  :class="{ musicPaused: !audio[index].isPlay }"
                ></image>
                <view class="tools" @click="play(index)">
                  <image :src="audio[index].isPlay ? icon.pause : icon.play"></image>
                </view>
              </view>
              <view class="gurudin-content">
                <view class="title">
                  {{ item.musicName }}
                  <view class="time"></view>
                </view>
                <view class="author">{{ item.musicAuthor }}</view>
              </view>
              <image
                @click="delCollect(item)"
                class="del"
                src="https://www.diandianyouke.site:801/fileDataBase/static/stag/static/img/icon_scangy.png"
                mode=""
              />
            </view>
          </label>
        </radio-group>
      </view>
      <view class="bottom-btn">
        <view class="all" @click="checkAll">
          <aip-checkbox :key="keys" :check="isAll"></aip-checkbox>
          全选</view
        >
        <button class="verify" @click="verify">
          确认选择{{ music.length ? `(${music.length})` : "" }}
        </button>
      </view>
    </view>
  </uni-popup>
</template>

<script>
import { log } from "console";
import { httpRequest } from "../../utils/http";
import { onUnload } from "@dcloudio/uni-app";
import tips from "../../components/index/tips.vue";
import btnModule from "../../components/index/btnModule.vue";
import aipCheckbox from "../../components/index/aip-checkbox.vue";

export default {
  components: {
    tips: tips,
    btnModule: btnModule,
    aipCheckbox: aipCheckbox,
  },
  name: "UniPresetVueVite1Music",
  data() {
    return {
      individuality: [],
      isShow: 0,
      shopCate1Id: 0,
      musicArr: [],
      musicId: -1,
      audioContexts: [],
      play: false,
      keys: 1,
      isAll: false,
      music: [],
      icon: {
        play:
          "",
        pause:
          "",
      },
      audio: [],
      content: "为了视频内容不重复,建议添加至少3首音乐,生成的视频将随机选择",
    };
  },
  onLoad(e) {
    this.shopCate1Id = uni.getStorageSync("shop")[e.index].shopCate1Obj.shopCate1Id;
    if (uni.getStorageSync("music")) {
      this.music = uni.getStorageSync("music");
    }
    if (this.music.length) {
      this.audioContent(this.music);
      this.getAudio(this.music);
    }
  },
  // onReachBottom() {
  //    this.getMusic()
  // },
  methods: {
    close() {
      this.$refs.add.close();
    },
    async delCollect(e) {
      await httpRequest("/api/delDiyMusic", "POST", { diyMusicId: e.musicId });
      this.getIndiv();
    },
    async getCollect(e, i) {
      if (e.isCollect) {
        await httpRequest("/api/delDiyMusic", "POST", { diyMusicId: e.musicId });
        this.getMusic();
      } else {
        const res = await httpRequest("/api/addDiyMusic", "POST", {
          businessId: uni.getStorageSync("business").businessId,
          musicId: e.musicId,
        });
        this.getMusic();
      }
    },
    delMusic(i) {
      this.audioContexts.map((e) => e.stop());
      this.audio.map((e) => (e.isPlay = false));
      this.music.splice(i, 1);
      uni.setStorageSync("music", this.music);
      uni.setStorageSync("musicArr", this.musicArr);
    },
    switchMusic(e) {
      if (this.music.length) {
        this.audioContexts.map((e) => e.stop());
        this.audio.map((e) => (e.isPlay = false));
      }
      console.log(e.show);
      if (e.show) {
        if (!this.musicArr.length) {
          this.getMusic();
        }
        setTimeout(() => {
          if (!this.music.length) return;
          for (let i = 0; i < this.music.length; i++) {
            console.log(this.music[i].musicId);
            console.log(this.musicArr);
            this.musicArr.forEach((e) => {
              if (this.music[i].musicId == e.musicId) {
                e.checked = true;
              }
            });
          }
        }, 1000);
        // for(let j = 0;j<this.musicArr.length;j++){
        //   for(let i = 0;i<this.music.length;i++){
        //     if(this.musicArr[j].musicId == this.music[i].musicId){
        //       this.musicArr[j].checked = true
        //     }else{
        //       this.musicArr[j].checked = false
        //     }
        //   }
        // }
      } else {
        if (this.music.length) {
          this.audioContexts.map((e) => e.stop());
          this.audio.map((e) => (e.isPlay = false));
        }
      }
    },
    verify() {
      this.$refs.add.close();
      this.audioContexts.map((e) => e.stop());
    },
    check(item, i) {
      item.checked = !item.checked;
      this.keys = this.keys == 1 ? 0 : 1;
      this.isAll = this.musicArr.every((e) => e.checked === true);
      //  this.music = this.musicArr.filter(e=>e.checked==true)
      if (item.checked) {
        this.music.push(item);
      } else {
        this.music = this.music.filter((e) => {
          return e.musicId != item.musicId;
        });
      }
      uni.setStorageSync("music", this.music);
    },
    checkAll() {
      if (this.isAll) {
        this.musicArr.forEach((e) => {
          e.checked = false;
        });
      } else {
        this.musicArr.forEach((e) => {
          e.checked = true;
        });
      }
      this.isAll = !this.isAll;
      this.music = this.musicArr.filter((e) => e.checked == true);
      uni.setStorageSync("music", this.music);
    },
    addMusic() {
      this.$refs.add.open("bottom");
    },
    play(i) {
      if (this.audio[i].isPlay) {
        // 暂停播放
        this.onPause(i);
      } else {
        // 开始播放
        this.onPlay(i);
      }
    },
    // playCall(src) {
    //     this.$refs.audioPlayers.forEach(e =>{
    //   if (src != e.src) {
    //     e.onPause();
    //   }
    // });
    // },

    //音频暂停
    onPause(i) {
      this.audio[i].isPlay = false;
      this.audioContexts[i].pause();
    },
    //音频播放
    onPlay(i) {
      this.audio.map((e) => (e.isPlay = false));
      this.audioContexts.map((e) => e.stop());
      this.audioContexts[i].onCanplay((e) => {});
      this.audio[i].isPlay = true;
      this.audioContexts[i].play();
      this.audioContexts[i].onTimeUpdate((e) => {
        console.log(JSON.stringify(e));
      });
      this.audioContexts[i].onError((err) => {
        console.log(err);
        this.audio[i].isPlay = false;
        // uni.showModal({
        //    title: '提示',
        //    content: '系统错误',
        //    showCancel: false
        //  });
      });
      this.audioContexts[i].onEnded((e) => {
        this.onPause(i);
      });
    },
    goBack() {
      uni.navigateBack({ delta: 1 });
    },
    queren() {
      uni.setStorageSync("music", this.musicId);
      uni.navigateBack({ delta: 1 });
    },
    radioChange(e) {
      this.musicId = e.detail.value;
      console.log(this.musicId);
    },
    choose(n) {
      this.isShow = n;
      console.log(this.audioContexts);
      this.audio.map((e) => (e.isPlay = false));
      this.audioContexts.map((e) => e.stop());
      this.audioContexts.map((e) =>
        e.onStop((res) => {
          console.log("停止");
          console.log(n);
        })
      );
      if (n == 0) {
        this.getMusic();
      }
      if (n == 1) {
        this.getIndiv();
      }
    },
    async delIndiv(id) {
      httpRequest("/api/delDiyMusic", "POST", { diyMusicId: id });
      uni.showToast({ title: "删除成功", icon: "none" });
      this.getIndiv();
    },
    //获取个性音乐
    async getIndiv() {
      const res = await httpRequest("/api/diyMusicList", "POST", {
        businessId: uni.getStorageSync("business").businessId,
      });
      if (!res.data) return uni.showToast({ title: "还没有添加个性音乐", icon: "none" });
      this.individuality = res.data;
      this.audioContent(this.individuality);
      this.getAudio(this.individuality);
    },
    //获取背景音乐
    async getMusic() {
      const res = await httpRequest("/api/musicRad", "POST", { shopCate1Id: 1 });
      console.log(res);
      this.musicArr = [...this.musicArr, ...res.data];
      const res1 = await httpRequest("/api/diyMusicList", "POST", {
        businessId: uni.getStorageSync("business").businessId,
      });
      this.individuality = res1.data;
      this.musicArr.forEach((e) => {
        e.checked = false;
        e.isCollect = false;
        if (!this.individuality) {
          return;
        } else {
          this.individuality.forEach((item) => {
            if (item.musicId == e.musicId) e.isCollect = true;
          });
        }
      });
      // this.musicArr.map(e=>{
      //     e.musicUrl = this.encodeAndJoinURL(e.musicUrl)
      // })
      console.log(this.musicArr);

      this.audioContent(this.musicArr);
      this.getAudio(this.musicArr);
    },
    audioContent(musicArr) {
      this.audioContexts = [];
      musicArr.forEach((audioItem, index) => {
        const audioContext = uni.createInnerAudioContext();
        audioContext.src = audioItem.musicUrl;
        this.audioContexts.push(audioContext);
      });
      console.log(this.audioContexts);
    },
    getAudio(music) {
      for (let i = 0; i < music.length; i++) {
        this.audio.push({
          /**
           * 是否正在播放
           * false=否 true=是
           */
          isPlay: false,

          /**
           * 当前播放时间
           */
          startTime: 0,

          /**
           * 音频总时长
           */
          duration: 0,

          /**
           * 播放进度
           */
          playProgress: 0,
        });
      }
    },
    encodeAndJoinURL(url) {
      const urlParts = url.split("/");
      const lastPart = urlParts[urlParts.length - 1];
      const chinesePart = lastPart.match(/[\u4e00-\u9fa5]+/g);

      if (chinesePart) {
        const encodedPart = encodeURIComponent(chinesePart[0]);
        const encodedURL = url.replace(chinesePart[0], encodedPart);
        return encodedURL;
      }

      return url;
    },
  },
  onHide() {
    this.audioContexts.map((e) => e.stop());
  },
  onUnload() {
    this.audioContexts.map((e) => e.stop());
  },
};
</script>

<style lang="scss" scoped>
.kong {
  display: flex;
  flex-direction: column;
  align-items: center;
  box-sizing: border-box;
  width: 100%;
  text-align: center;
  overflow: hidden;
  font-size: 24rpx;
  color: rgb(144, 147, 153);
  .img {
    width: 610rpx;
    height: 368rpx;
    margin-top: 132rpx;
    margin-bottom: 42rpx;
  }
}
.betitle {
  box-sizing: border-box;
  width: 690rpx;
  min-height: 142rpx;
  font-size: 28rpx;
  color: rgb(69, 70, 74);
  margin-bottom: 24rpx;
  .gurudin-audio {
    animation: mymove 0.5s;
    position: relative;
    height: 130rpx;
    border-radius: 8rpx;
    clear: both;
    width: 100%;
    display: flex;

    .gurudin-poster,
    .gurudin-content {
      float: left;
    }
    .del {
      width: 48rpx;
      height: 48rpx;
    }

    .gurudin-poster {
      position: relative;
      width: 130rpx;
      height: 126rpx;
      margin-top: 1rpx;
      margin-left: 1rpx;
      border-top-left-radius: 8rpx;
      border-bottom-left-radius: 8rpx;

      image {
        width: 110rpx;
        height: 110rpx;
        margin: 10rpx;
        opacity: 0.8;
        border-radius: 100%;
      }

      .tools {
        position: absolute;
        text-align: center;
        top: 0;
        left: 0;
        height: 130rpx;
        width: 130rpx;

        image {
          width: 50rpx;
          height: 50rpx;
          margin-top: calc((100% - 50rpx) / 2);
        }
      }
    }

    .gurudin-content {
      width: calc(100% - 130rpx - 62rpx);
      height: calc(130rpx - 60rpx);
      padding: 30rpx;
      white-space: nowrap; /* 禁止换行 */
      overflow: hidden; /* 隐藏超出部分 */
      text-overflow: ellipsis; /* 使用省略号表示被隐藏的文本 */

      .title {
        position: relative;
        font-size: 28rpx;
        height: 40rpx;

        .time {
          position: absolute;
          right: 0;
          top: 0;
          font-size: 24rpx;
        }
      }

      .author {
        margin-top: 10rpx;
        font-size: 24rpx;
      }
    }
  }
  .circle {
    width: 48rpx;
    height: 48rpx;
    border-radius: 356rpx;
    background-color: rgb(197, 163, 255);
    text-align: center;
    line-height: 48rpx;
    color: #fff;
  }
}
.popup {
  width: 100%;
  background-color: #fff;
  border-radius: 32rpx 32rpx 0 0;
}
.recom {
  font-size: 32rpx;
  height: 108rpx;
  line-height: 108rpx;
}
.close-btn {
  position: absolute;
  top: 30rpx;
  left: 30rpx;
  width: 48rpx;
  height: 48rpx;
}
.audio {
  width: 590rpx;
  height: 126rpx;
  margin-left: 40rpx;
}
.active {
  color: rgba(142, 84, 244, 1);
  border-bottom: 2px solid rgba(142, 84, 244, 1);
}
.box-bottom {
  height: 160rpx;
  width: 100%;
  position: fixed;
  bottom: 0rpx;
  left: 0;
  background-color: #fff;
  z-index: 9;
  .bottom {
    position: fixed;
    bottom: 34rpx;
    left: 0;
    display: flex;
    justify-content: space-between;
    width: 100%;
    background-color: #fff;
    .bottom-quxiao {
      width: 330rpx;
      height: 86rpx;
      text-align: center;
      line-height: 88rpx;
      color: rgba(142, 84, 244, 1);
      border: 1px solid rgba(142, 84, 244, 1);
    }
    .bottom-queren {
      width: 332rpx;
      height: 88rpx;
      text-align: center;
      line-height: 88rpx;
      background-color: rgba(142, 84, 244, 1);
      color: #fff;
    }
  }
}

.label {
  display: flex;
  align-items: center;
  margin-top: 20rpx;
  .light {
    border: 2rpx solid #e8eaec;
    background: #fff;

    .gurudin-poster {
      background: #dcdee2;
    }

    .gurudin-content {
      .title {
        color: #2c405a;

        .time {
          color: #808695;
        }
      }

      .author {
        color: #808695;
      }
    }
  }

  .dark {
    border: 2rpx solid #17233d;
    background: #515a6e;

    .gurudin-poster {
      background: #17233d;
    }

    .gurudin-content {
      .title {
        color: #ffffff;

        .time {
          color: #c5c8ce;
        }
      }

      .author {
        color: #c5c8ce;
      }
    }
  }

  .gurudin-audio {
    animation: mymove 0.5s;
    position: relative;
    height: 130rpx;
    border-radius: 8rpx;
    clear: both;
    width: 100%;
    display: flex;
    align-items: center;
    padding-right: 30rpx;

    .gurudin-poster,
    .gurudin-content {
      float: left;
    }
    .del {
      width: 48rpx;
      height: 48rpx;
    }
    .gurudin-poster {
      position: relative;
      width: 130rpx;
      height: 126rpx;
      margin-top: 1rpx;
      margin-left: 1rpx;
      border-top-left-radius: 8rpx;
      border-bottom-left-radius: 8rpx;

      image {
        width: 110rpx;
        height: 110rpx;
        margin: 10rpx;
        opacity: 0.8;
        border-radius: 100%;
      }

      .tools {
        position: absolute;
        text-align: center;
        top: 0;
        left: 0;
        height: 130rpx;
        width: 130rpx;

        image {
          width: 50rpx;
          height: 50rpx;
          margin-top: calc((100% - 50rpx) / 2);
        }
      }
    }

    .gurudin-content {
      width: calc(100% - 130rpx - 62rpx);
      height: calc(130rpx - 60rpx);
      padding: 30rpx;
      white-space: nowrap; /* 禁止换行 */
      overflow: hidden; /* 隐藏超出部分 */
      text-overflow: ellipsis; /* 使用省略号表示被隐藏的文本 */

      .title {
        position: relative;
        font-size: 28rpx;
        height: 40rpx;

        .time {
          position: absolute;
          right: 0;
          top: 0;
          font-size: 24rpx;
        }
      }

      .author {
        margin-top: 10rpx;
        font-size: 24rpx;
      }
    }
  }

  @keyframes mymove {
    from {
      opacity: 0;
    }

    to {
      opacity: 1;
    }
  }

  // 旋转动画
  .musicRotate {
    animation: rotate 10s linear infinite;
  }

  @keyframes rotate {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(359deg);
    }
  }

  .musicPaused {
    animation-play-state: paused;
  }
}
.bottom-btn {
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  width: 100%;
  height: 166rpx;
  padding: 10rpx 30rpx 0;
  background-color: #fff;
  .all {
    display: flex;
    align-items: center;
    height: 88rpx;
    font-size: 28rpx;
    color: rgb(144, 147, 153);
  }
  .verify {
    width: 552rpx;
    height: 86rpx;
    padding: 0;
    margin: 0;
    text-align: center;
    line-height: 86rpx;
    color: #fff;
    background-color: rgb(142, 84, 244);
    font-size: 32rpx;
    margin-left: 18rpx;
  }
}
</style>
